<template>
    <el-card class="box-card" style="border-right: none; border-bottom: none !important; border-top: none !important;border-radius: 0;">
        <div class="card-header">
            <span>任务订单管理</span>
        </div>
        <el-form :inline="true" :model="formInline" class="form-inline">
            <el-form-item label="用户名">
                <el-input v-model="formInline.username" placeholder="用户名" clearable />
            </el-form-item>
            <el-form-item label="单号">
                <el-input v-model="formInline.order_sn" placeholder="单号" clearable />
            </el-form-item>
            <el-form-item label="状态">
                <el-select
                v-model="formInline.state"
                placeholder="状态"
                clearable
                >
                <el-option v-for="(txt, index) in statusTextArray" :key="index" :label="txt" :value="index" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="mb-4" v-if="selectedItems.length > 0">
          <el-button 
            type="success" 
            :disabled="!selectedItems.length"
            @click="batchApprove"
            size="small"
          >
            批量通过 ({{ selectedItems.length }})
          </el-button>
          
          <el-button 
            type="danger" 
            :disabled="!selectedItems.length"
            @click="batchReject"
            size="small"
          >
            批量拒绝
          </el-button>

          <el-button 
            type="warning" 
            :disabled="!selectedItems.length"
            @click="batchCancel"
            size="small"
          >
            批量撤销
          </el-button>
        </div>

        <el-table :data="taskOrderList" ref="multipleTableRef" height="600px" style="width: 100%"  v-loading="loading" @selection-change="handleSelectionChange">
           
            <el-table-column type="selection" width="55" />
            <!-- 渲染单号 -->
            <el-table-column prop="order_sn" label="单号" min-width="150" />

            <!-- 渲染手机号 -->
            <el-table-column prop="price" label="金额" min-width="150" />

            <!-- 任务名称 -->
            <el-table-column prop="task_name" label="任务名称" min-width="150" />

             <!-- VIP -->
             <el-table-column prop="vip_price" label="VIP金额" min-width="150" />

            <!-- 渲染用户名 -->
            <el-table-column prop="username" label="用户名" min-width="150" />

            <el-table-column prop="nickname" label="用户昵称" min-width="150" />

            <!-- 渲染手机号 -->
            <el-table-column prop="phone" label="手机号" min-width="150" />

            <!-- 渲染状态 -->
            <el-table-column label="状态" min-width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === -1 ? 'danger' : scope.row.status === 0 ? 'primary' : 'info'" @click="handleEditStatus(scope.$index, scope.row)"
                        style="cursor: pointer;"
                    >
                        {{ scope.row.status_text }}
                    </el-tag>
                </template>
            </el-table-column>

            <el-table-column prop="notes" label="拒绝原因" width="260" />
            <!-- 渲染创建时间 -->
            <el-table-column prop="created_at" label="提交时间" width="160" />
            <el-table-column prop="audit_time" label="审核时间" width="160" />
            <!-- 渲染更新时间 -->
            <el-table-column prop="updated_at" label="更新时间" width="160" />

            <!-- 操作 -->
            <el-table-column fixed="right" label="操作" width="200" >
            <template #default="scope">
                <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
                <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                <el-button size="small" @click="handleView(scope.$index, scope.row)">查看</el-button>
            </template>
            </el-table-column>
        </el-table>
        <el-pagination class="el-p"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
    </el-card>

    <!-- 编辑管理员对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="订单状态"
    width="500px"
    :close-on-click-modal="false"
  >
    <TaskStatusEdit ref="addFormRef" :formData="currentFormData" is-edit="edit" :statuslist="statusTextArray" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <el-drawer
    v-model="drawerVisible"
    title="任务订单详情"
    direction="rtl"
    size="50%"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="单号">{{ currentFormData?.order_sn }}</el-descriptions-item>
      <el-descriptions-item label="金额">{{ currentFormData?.price }}</el-descriptions-item>
      <el-descriptions-item label="用户名">{{ currentFormData?.username }}</el-descriptions-item>
      <el-descriptions-item label="用户昵称">{{ currentFormData?.nickname }}</el-descriptions-item>
      <el-descriptions-item label="任务数据">{{ currentFormData?.task_data }}</el-descriptions-item>
      <el-descriptions-item label="任务图片">
        <div v-if="currentFormData?.imgs && currentFormData.imgs.length > 0">
          <el-image
            v-for="(img, index) in currentFormData.imgs"
            :key="index"
            :src="img"
            style="margin-right: 10px; width: 100px; height: 100px; object-fit: cover;"
            fit="cover"
            lazy
            :preview-src-list="currentFormData.imgs"
            :initial-index="index"
          />
        </div>
        <span v-else>暂无图片</span>
      </el-descriptions-item>
      <el-descriptions-item label="任务名称">{{ currentFormData?.task_name }}</el-descriptions-item>
      <el-descriptions-item label="VIP金额">{{ currentFormData?.vip_price }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="currentFormData?.status === 1 ? 'success' : currentFormData.status === -1 ? 'danger' : currentFormData.status === 0 ? 'primary' : 'info'" >
            {{ currentFormData?.status_text }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="拒绝原因">{{ currentFormData?.notes}}</el-descriptions-item>
      <el-descriptions-item label="审核时间">{{ currentFormData?.audit_time }}</el-descriptions-item>
      <el-descriptions-item label="提交时间">{{ currentFormData?.created_at }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ currentFormData?.updated_at }}</el-descriptions-item>
    </el-descriptions>
  </el-drawer>
</template>
<script setup>
import { ref, reactive, watch, computed } from 'vue';
import { taskOrderService } from '@/api/taskOrderService';
import { ElMessage, ElMessageBox } from 'element-plus';
import TaskStatusEdit from '@/components/TaskStatusEdit.vue';

const currentPage = ref(1)  // 默认第一页
const pageSize = ref(10)    // 默认每页10条
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const dialogVisible = ref(false);
const total = ref(0);
const dialogType = ref('add');
const currentFormData = ref(null);
const addFormRef = ref(null);
const drawerVisible = ref(false);
const loading = ref(true); // 加载状态
const statusTextArray = ref();
const formInline = reactive({
    username: '',
    state: '',
    order_sn:''
});
const taskOrderList = ref([]);

const multipleTableRef = ref()

const selectedItems = ref([])

const handleSelectionChange = (val) => {
  selectedItems.value = val
}

const statusTagType = (status) => {
  const types = ['warning', 'success', 'danger']
  return types[status] || ''
}

const statusText = (status) => {
  const texts = ['待审核', '已通过', '已拒绝']
  return texts[status] || '未知状态'
}

// Convert formInline.statusText object into an array for rendering
const getStatusText = async () => {
    const response = await taskOrderService.getStatusText();
    statusTextArray.value=response || {};
};

getStatusText();

// 获取用户列表数据
const fetchTaskOrder = async () => {
    loading.value = true;
    try {
      const params = {
        username: formInline.username,
        status: formInline.state,
        order_sn:formInline.order_sn,
        page: currentPage.value,
        pageSize: pageSize.value
      };
      const response = await taskOrderService.getList(params);
      taskOrderList.value = response.data || [];
      total.value = response.total || 0;
    } catch (error) {
      ElMessage.error('获取用户列表失败');
      taskOrderList.value = [];
      total.value = 0;
    }finally {
      loading.value = false; // 停止加载状态
    }
};

fetchTaskOrder();

const onSubmit = () => {
    fetchTaskOrder();
};
const resetForm = () => {
    formInline.username = '';
    formInline.state = '';
    formInline.order_sn ='';
};

const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchTaskOrder();
};
const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchTaskOrder();
};
// 监听对话框关闭事件
watch(dialogVisible, (newVal) => {
    if (!newVal) {
      resetDialog();
    }
});

// 重置对话框状态
const resetDialog = () => {
    currentFormData.value = null;
    if (addFormRef.value) {
      addFormRef.value.resetForm();
    }
};

/**
* 处理删除管理员的操作
* @param {Object} row - 包含管理员信息的对象，用于标识要删除的管理员
*/
const handleDelete = async (row) => {
    try {
      // 弹出确认对话框，询问用户是否确定要删除指定的管理员
      await ElMessageBox.confirm(
        `确定要删除 ${row.order_sn} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      );

      // 调用后端接口删除指定ID的管理员
      await taskOrderService.del(row.id);
      ElMessage.success('删除成功');
      // 重新获取用户列表数据
      fetchTaskOrder();
    } catch (error) {

    }
};

const handleEditStatus  = (index, row) => {
    dialogType.value = 'edit';
    currentFormData.value = { ...row };
    dialogVisible.value = true;
};

const submitForm = async () => {
    console.log(addFormRef.value)
    // 检查表单引用是否存在
    if (!addFormRef.value) return;

    try {
        // 复制表单数据
        const formData = { ...addFormRef.value.form };
        // 更新管理员信息
        await taskOrderService.update(formData.id,formData).then(() => {
            // 处理更新操作成功的情况
            ElMessage.success('更新成功');
            // 关闭对话框
            dialogVisible.value = false;
            // 刷新用户列表
            fetchTaskOrder();
        });

    } catch (error) {
      // 处理添加或更新操作失败的情况
      //ElMessage.error(dialogType.value === 'add' ? '新增失败' : '更新失败');
    }
  };
  const handleView = (index, row) => {
    currentFormData.value = { ...row };
    drawerVisible.value = true;
  };

watch(currentFormData, (newVal) => {
  if (newVal && typeof newVal.imgs === 'string') {
    try {
      currentFormData.value.imgs = JSON.parse(newVal.imgs);
    } catch (error) {
      console.error('图片数据解析失败:', error);
      currentFormData.value.imgs = [];
    }
  }
});

const batchApprove = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }
  
  ElMessageBox.confirm(
    `确定通过选中的 ${selectedItems.value.length} 项申请吗?`,
    '确认通过',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success',
    }
  ).then(() => {
    const ids = selectedItems.value.map(item => item.id)
    // 调用API批量通过
    batchUpdateStatus(ids, 1).then(() => {
      fetchTaskOrder() // 重新获取数据
      multipleTableRef.value.clearSelection() // 清空选择
    })
  }).catch(() => {
    // 用户点击取消时不会抛出未捕获异常
    // 可以根据需要添加提示或忽略
  })
}

const batchReject = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }
  
  ElMessageBox.prompt('请输入拒绝理由', '确认拒绝', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^.{4,}$/,
    inputErrorMessage: '拒绝理由至少4个字符',
    type: 'error',
  }).then(({ value }) => {
    const ids = selectedItems.value.map(item => item.id)
    // 调用API批量拒绝
    batchUpdateStatus(ids, -1, value).then(() => {
      multipleTableRef.value.clearSelection()
    })
  }).catch(() => {
    // 用户点击取消时不会抛出未捕获异常
    // 可以根据需要添加提示或忽略
  })
}

const batchCancel = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }
  
  ElMessageBox.confirm(
    `确定撤销选中的 ${selectedItems.value.length} 项申请吗?`,
    '确认撤销',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success',
    }
  ).then(() => {
    const ids = selectedItems.value.map(item => item.id)
    // 调用API批量撤销
    batchUpdateStatus(ids, 2).then(() => {
      fetchTaskOrder() // 重新获取数据
      multipleTableRef.value.clearSelection() // 清空选择
    })
  }).catch(() => {
    // 用户点击取消时不会抛出未捕获异常
    // 可以根据需要添加提示或忽略
  })
}

// API调用示例
const batchUpdateStatus = async (ids, status, notes = '') => {
  // 这里替换为实际API调用
  console.log(`批量更新状态: ${ids.join(',')} 为 ${status}, 理由: ${notes}`)
  loading.value = true;
  taskOrderService.batchUpdateStatus(ids, status, notes).then(res => {
    console.log(`batchUpdateStatus:`,res.data.data)
    ElMessage.success(res.data.data)
    fetchTaskOrder()
  }).finally(() => {
    loading.value = false
  });

}
</script>
<style scoped>
.form-inline {
    margin: 20px 0;
    border-bottom: 1px solid #e4e7ed;
}
.el-p{
    margin-top: 15px;
    display: flex;
    justify-self: flex-end;
}
.el-select{
    width: 85px;
}
.card-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-bottom: 1px solid #e4e7ed;
}
</style>
